package util.io;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import util.parser.wikiXML.AnchorExtractor;

public class ZipInput {

	/**
	 * @param args
	 */

	private ZipFile zipFile = null;

	LinkedList<FileInput> list = null;
	
	LinkedList<InputStream> list_stream = null;

	public ZipInput(String filename) {

		try {
			zipFile = new ZipFile(filename);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		String path = "/media/sata/data/wikipedia/en/wikixml-20080724/borreme/p161nnnnn.zip";

		ZipInput zip = new ZipInput(path);

		LinkedList<FileInput> list = zip.getZipFiles();

		for (int i = 0; i < list.size(); i++) {

			FileInput in = list.get(i);

			System.out.println("-------------------------------\n");
			System.out.println(in.getText());

		}

		zip.close();

	}

	public LinkedList<FileInput> getZipFiles() {

		list = new LinkedList<FileInput>();
		try {

			Enumeration<? extends ZipEntry> enu = zipFile.entries();
			while (enu.hasMoreElements()) {

				ZipEntry entry = enu.nextElement();
				InputStream is = zipFile.getInputStream(entry);
				BufferedReader br = new BufferedReader(new InputStreamReader(
						is, "utf8"));

				FileInput in = new FileInput(br);

				list.add(in);

				// ZipFile->InputStream->BufferedInputStream->ByteArrayOutputStream->byte[]

				// byte[]->ByteArrayInputStream->InputStreamReader->BufferedReader

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}

	
	public LinkedList<InputStream> getZipFilesInputStream() {

		list_stream = new LinkedList<InputStream>();
		try {

			Enumeration<? extends ZipEntry> enu = zipFile.entries();
			while (enu.hasMoreElements()) {

				ZipEntry entry = enu.nextElement();
				InputStream is = zipFile.getInputStream(entry);

				list_stream.add(is);

			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list_stream;
	}
	
	public void close() {

		for (int i = 0; list != null && i < list.size(); i++) {
			list.get(i).close();
		}

		try {

			for (int i = 0; list_stream != null && i < list_stream.size(); i++) {
				list_stream.get(i).close();
			}

			zipFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		list = null;
		list_stream = null;
		zipFile = null;

	}

}
